Numbers

Today we shall be discussing floats and integers. The good news is that most of the stuff we shall be covering today should be intuitive. Okay, let’s get moving...

Integers

Integers are whole numbers like -6, 10, 1066 etc. In Python, integers work much in the same way they do in mathematics.

There are two main ways to create integers within Python:

  1. Just type a number into the console. Yeah, its that easy!
  2. use a special built-in function called 'int'.

Every data-type in Python has a function that can be used to convert objects into that type, for example, lists have the list() function, strings have the str() function and so on. Unsurprisingly then int() is used to convert non-integers into integers. For example, if I have the string “1066” I can use int() to convert it.


In [1]:
string_number = "1066"
integer = int(string_number)

print(int(integer))
print(type(integer))  # <-- the type function returns the type of the object passed in eg 1 is an integer, "hi" is a string, etc.


1066
<class 'int'>

The int() function also takes an optional argument base as well. So for example “1111”, base=2 will treat “1111” as a binary number and will return whatever that number is in base 10.


In [1]:
int("1111", base = 2)


Out[1]:
15

If we give the int function a float (more on them later) it will return the integer part of the number. Take care to note it always rounds down.


In [3]:
int(6.99999999999999)


Out[3]:
6

Integer Methods

If we have two integer numbers (lets say A and B), then you probably won't be suprised to hear that we can add, subtract, and multiply those numbers together. The symbols for those commands are as follows:


In [4]:
a = 10
b = 5

print(a +  b)  # addition
print(a -  b)  # subtraction
print(a *  b)  # multiplication
print(a ** b)  # exponentation
print(a %  b)  # modular arithmetic
print(a /  b)  # divsion (note, returns a float! Also, Python2 and Python3 act differently here, so beware!)
print(a // b)  # integer division

# For negative numbers, just add a "-" symbol before the number, for example:
print(-a, a)


15
5
50
100000
0
2.0
2
-10 10

Modular Arithmetic

Modular Arithmetic is something you can learn more about here. I’m going to skip most of the math and just show you a few common uses:

  • Work out if B is a divisor of A (If not, we get the remainder)
  • Creating numerical cycles (eg, 121212121...)
  • Grabbing the last n digits of a number.

divisors...

A % B gives the remainder of A / B. Thus if A % B is 0 then that means the B must be a divisor of A. Ergo if x % 2 equals zero then that means x is an even number.

'cycles'...

As for cycles, an obvious use for this is stuff like measuring time, a clocks hand resets after hitting 60:

58 % 60 = 58
59 % 60 = 59
60 % 60 = 0    ←- count ‘resets’
61 % 60 = 1
62 % 60 = 2

Once we hit 61 secs then we would prefer to set the secs timer back to zero and update minutes. thus 61 secs becomes 1min 1sec

getting n last digits...

And finally, you can get last digits of a number by using x % (power of 10). A load of examples are printed in the console below.


In [36]:
# Grabbing the last digit:
print(123423420 % 10)
print(1234234231 % 10)
print(12342342302 % 10)
print(123423423023 % 10)
print(1234234230244 % 10)
print(12342342302445 % 10)

print("\n")

# Grabbing the last 3 digits:
print(12342342302445 % 1000)
print(1234234230244 % 1000)
print(123423423023 % 1000) # <-- note 0 is dropped, integers cannot start with a 0. Thus 023 is simply 23

print("\n")

# grabbing the last 6 digits
print(12342342302 % 1000000)
print(123423423 % 1000000)
print(1234567 % 1000000)
print(12345 % 1000000)


0
1
2
3
4
5


445
244
23


342302
423423
234567
12345

Integer Divsion

Integer division returns the whole number part of A / B. for example, 10 // 6 is 1 because 6 fits into 10 exactly once (12 // 6 is of course 2).

So modulo in conjunction with integer division can get you both the whole part of A/B and the remainder of A/B

10 // 6  = 1
10 % 6   = 4 
10 / 6   = 1.6666666666666667

Combine these two operations and you can make a nice clock:


In [5]:
def time(time):
    """time measured in total elapsed minutes, function converts to days, hours, mins"""
    t = time // 60
    days  = t // 24 # 24 hours in a day
    hours = t %  24 # after working out number of days, get leftover hours
    mins =  time % 60
    return "Input in mins = '{}' which is: {} days {} hours and {} mins".format(time, days, hours, str(mins).zfill(2))

print(time(1))
print(time(60))
print(time(61))
print(time(960))
print(time(1440))
print(time(1447))
print(time(33456456))


Input in mins = '1' which is: 0 days 0 hours and 01 mins
Input in mins = '60' which is: 0 days 1 hours and 00 mins
Input in mins = '61' which is: 0 days 1 hours and 01 mins
Input in mins = '960' which is: 0 days 16 hours and 00 mins
Input in mins = '1440' which is: 1 days 0 hours and 00 mins
Input in mins = '1447' which is: 1 days 0 hours and 07 mins
Input in mins = '33456456' which is: 23233 days 15 hours and 36 mins

Floats

What are floating-point numbers?

Well, they are a bit like decimal numbers in Math (Warning! this is an over-simplification, in numbers part 2 I will go into more depth).

Just like Integers there are two main ways to create them:

  1. Just type a floating point number, e.g 3.14
  2. Or we can use the 'float' built-in method

Floats have more or less the same methods as integers do (e.g +-/*%//). Similarly the float() function works remarkably similar to the int function.


In [20]:
string_number = "10.66"
print(float(string_number))


print(float(-3.2e20)) # < -- Python supports scientific notation...
print(float('inf'))   # < -- Python also has a way of representing infinity
print(float(0), float(10), float(5), sep="\n") # notice that when 'float' gets an integer as input '.0' is added to the number


10.66
-3.2e+20
inf
0.0
10.0
5.0

Dividing by Zero

Dividing by zero is something you are not allowed to do in mathmatics, Python is no different. If you try and divide by zero Python will simply throw and error. If you try to modulo by zero or use integer divsion you will get the same error.


In [89]:
30 / 0


---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-89-478a8a99f756> in <module>()
----> 1 30 / 0

ZeroDivisionError: division by zero

In [8]:
30 % 0


---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-8-830f8b6f3cd5> in <module>()
----> 1 30 % 0

ZeroDivisionError: integer division or modulo by zero

In [9]:
30 // 0


---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-9-180e3438e879> in <module>()
----> 1 30 // 0

ZeroDivisionError: integer division or modulo by zero

Order of Operations

The order of operations (sorted by highest-to-lowerest precidence) in Python is the following:

  1. Parentheses
  2. Exponentiation
  3. Multiplication
  4. Division
  5. Addition
  6. Subtraction

A few examples...


In [21]:
## The only difference a-through-f is where we put a pair of parentheses.
a = 30 - 6 ** 4 * 30 + 20 / 2 
b = (30 - 6) ** 4 * 30 + 20 / 2 
c = 30 - 6 ** (4 * 30) + 20 / 2 
d = 30 - 6 ** 4 * (30 + 20) / 2 
e = 30 - 6 ** (4 * 30 + 20 / 2) 
f = 30 - (6 ** 4 * 30 + 20 / 2) 

print(a, b, c, d, e, f, sep= "\n")


-38840.0
9953290.0
-2.38863639936011e+93
-32370.0
-1.444317089237147e+101
-38860.0

So thats some basic mathmatics for you. Python does have support for fractions, complex numbers and a bunch of other stuff as well. But if you want that functionality you have to go hunting for it.

For example, suppose I want the log(x) or the sqrt(x) what can I do?


In [1]:
from math import log2, sqrt

print(sqrt(100))
## Alternatively, you can also get the square root of a number by raising it to the 0.5 power
print(100**0.5)

print(log2(100))


10.0
10.0
6.643856189774724

You might be wondering why I didn't get a name error here. Well, thats because the import statement on the first line tell Python where the definition of log2 and sqrt are; i.e. they come from the math module.

Alright thats it for today. In the next lecture we will go into a bit more detail.


In [ ]: